<template>
  <el-dialog :visible="value" :before-close="cancel">
    <template slot="title">{{isCreated ? '新增代理' : '编辑代理'}}</template>
    <el-form :model="form" :rules="refRules" ref="form" label-width="150px">
      <template v-if="isCreated">
        <el-form-item label="用户名" prop="username" :error="userCheck">
          <el-col :span="16">
            <el-input
              v-model="form.username"
              placeholder="请输入用户名"
              @change="agencyCheck"
              @keyup.enter.native="submitForm('form')"
            ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-col :span="16">
            <el-input
              type="password"
              v-model="form.password"
              placeholder="8-20个数字/字母/特殊字符组成"
              @keyup.enter.native="submitForm('form')"
            ></el-input>
          </el-col>
        </el-form-item>
        <!-- 代理类型:返佣模式 to do, 需增加权限控制 -->
        <el-form-item label="代理类型">
          <el-col :span="16">
            <el-radio-group v-model="form.rebate">
              <el-radio :label="1">外部代理</el-radio>
              <el-radio :label="2">内部代理</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item label="所属上级">
          <el-col :span="16">
            <el-input
              v-model="form.proxy"
              placeholder="请输入所属上级"
              @keyup.enter.native="submitForm('form')"
            ></el-input>
          </el-col>
        </el-form-item>
      </template>
      <template v-else>
        <el-form-item label="用户名">
          <el-col :span="16">
            <span>{{form.username}}</span>
          </el-col>
        </el-form-item>
        <el-form-item label="所属上级">
          <el-col :span="16">
            {{form.proxy}}
          </el-col>
        </el-form-item>
        <el-form-item label="代理类型">
          <el-col :span="16">
            <el-radio-group v-model="form.rebate">
              <el-radio :label="1">外部代理</el-radio>
              <el-radio :label="2">内部代理</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
      </template>
      <el-form-item>
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </el-form-item>
      <el-form-item v-if="isCreated">
        <p class="attention-text">注：所属上级默认为admin，可以填写其他代理，设定后无法再次修改</p>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>

// mixins
import { form, grid, factory } from '@/build';

// services
import { updateAgencyCommission } from '@/services/api/agency';
import { validateAdjustmentUsers } from '@/services/api/adjustment';

export default {
  name: 'edit-agency-dialog',
  props: ['value', 'id', 'rowData'],
  mixins: [form, grid, factory],
  data() {
    return {
      userCheck: '',
      form: {
        username: undefined,
        password: undefined,
        proxyId: this.id,
        ruleId: (this.rowData && this.rowData.feeRuleNextId) ? this.rowData.feeRuleNextId : null,
        rebate: 1,
        proxy: 'admin',
      },
      refRules: {
        username: factory.getRule('username'),
        password: factory.getRule('passwordMixType'),
        ruleId: { required: true, message: '手续费方案为必选项' },
      },
    };
  },
  computed: {
    isCreated() {
      return !this.id;
    },
  },
  methods: {
    cancel() {
      this.$emit('input', false);
    },
    submitForm(formName) {
      if (this.form.proxy.trim() === '') {
        this.form.proxy = 'admin';
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.doSave({ action: 'saveForm', form: formName });
          this.cancel();
        }
      });
    },
    async agencyCheck() {
      this.userCheck = '';
      try {
        const [status, result] = await validateAdjustmentUsers({ users: this.form.username });
        if (!status) throw new Error(result.message);
        if (result.length) return;
        this.userCheck = '用户已存在';
      } catch (e) {
        this.$message({
          type: 'error',
          message: `${e.message || ''}`,
        });
      }
    },
  },
  mounted() {
    this.getAll();
    this.bindSave(updateAgencyCommission, 'saveForm', 'form', {
      beforeSend: data => ({
        ...data,
        uid: this.id,
      }),
      afterSuccess: () => {
        setTimeout(() => {
          this.$parent.getAll();
        }, 2000);
      },
    });
  },
};
</script>

<style scoped>
.attention-text {
  color: grey;
}
</style>
